import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:image_picker/image_picker.dart';

// 反馈类型枚举（保留原有逻辑，优化构造函数可读性）
enum FeedbackType {
  bug('Bug Report', Icons.bug_report, Color(0xFFE74C3C)),
  feature('Feature Request', Icons.lightbulb_outline, Color(0xFF3498DB)),
  improvement('Improvement', Icons.trending_up, Color(0xFF2ECC71)),
  other('Other', Icons.help_outline, Color(0xFF9B59B6));

  const FeedbackType(this.label, this.icon, this.color);
  final String label;
  final IconData icon;
  final Color color;
}

// 反馈表单状态管理（保留原有逻辑）
final feedbackTypeProvider =
    StateProvider<FeedbackType>((ref) => FeedbackType.bug);
final feedbackContentProvider = StateProvider<String>((ref) => '');
final contactInfoProvider = StateProvider<String>((ref) => '');
final selectedImagesProvider = StateProvider<List<File>>((ref) => []);
final isSubmittingProvider = StateProvider<bool>((ref) => false);

class FeedbackScreen extends ConsumerStatefulWidget {
  const FeedbackScreen({super.key});

  @override
  ConsumerState<FeedbackScreen> createState() => _FeedbackScreenState();
}

class _FeedbackScreenState extends ConsumerState<FeedbackScreen> {
  final _formKey = GlobalKey<FormState>();
  final _contentController = TextEditingController();
  final _contactController = TextEditingController();
  final ImagePicker _picker = ImagePicker();

  // 修复：添加权限状态跟踪（避免重复请求权限导致崩溃）
  bool _hasPermissionDenied = false;

  @override
  void initState() {
    super.initState();
    // 初始化时同步控制器与Provider值（避免数据不一致）
    final initialContent = ref.read(feedbackContentProvider);
    final initialContact = ref.read(contactInfoProvider);
    if (initialContent.isNotEmpty) _contentController.text = initialContent;
    if (initialContact.isNotEmpty) _contactController.text = initialContact;

    // 监听文本变化，同步更新Provider
    _contentController.addListener(() {
      ref.read(feedbackContentProvider.notifier).state =
          _contentController.text;
    });
    _contactController.addListener(() {
      ref.read(contactInfoProvider.notifier).state = _contactController.text;
    });
  }

  @override
  void dispose() {
    // 修复：移除监听器后再释放控制器，避免内存泄漏
    _contentController.removeListener(() {});
    _contactController.removeListener(() {});
    _contentController.dispose();
    _contactController.dispose();
    super.dispose();
  }

  // 选择图片（修复：添加权限判断、图片大小限制）
  Future<void> _pickImage() async {
    // 1. 检查图片数量限制
    final selectedImages = ref.read(selectedImagesProvider);
    if (selectedImages.length >= 3) {
      _showSnackBar('Maximum 3 images allowed', isError: true);
      return;
    }

    // 2. 检查权限状态（避免重复请求）
    if (_hasPermissionDenied) {
      _showPermissionDialog();
      return;
    }

    try {
      final XFile? image = await _picker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 1920,
        maxHeight: 1080,
        imageQuality: 85,
      );

      // 3. 处理选择结果
      if (image != null) {
        final imageFile = File(image.path);
        // 额外校验：避免空文件和过大文件（>10MB）
        if (await imageFile.length() > 10 * 1024 * 1024) {
          _showSnackBar(
              'Image size exceeds 10MB. Please select a smaller image.',
              isError: true);
          return;
        }
        ref
            .read(selectedImagesProvider.notifier)
            .update((state) => [...state, imageFile]);
      }
    } catch (e) {
      // 4. 捕获权限拒绝错误（区分普通错误）
      if (e.toString().contains('permission') ||
          e.toString().contains('denied')) {
        _hasPermissionDenied = true;
        _showPermissionDialog();
      } else {
        _showSnackBar('Failed to pick image: ${e.toString().substring(0, 50)}',
            isError: true);
      }
    }
  }

  // 拍照（修复：同选择图片的权限与大小校验）
  Future<void> _takePhoto() async {
    final selectedImages = ref.read(selectedImagesProvider);
    if (selectedImages.length >= 3) {
      _showSnackBar('Maximum 3 images allowed', isError: true);
      return;
    }

    if (_hasPermissionDenied) {
      _showPermissionDialog();
      return;
    }

    try {
      final XFile? image = await _picker.pickImage(
        source: ImageSource.camera,
        maxWidth: 1920,
        maxHeight: 1080,
        imageQuality: 85,
        preferredCameraDevice: CameraDevice.rear, // 优先使用后置摄像头
      );

      if (image != null) {
        final imageFile = File(image.path);
        if (await imageFile.length() > 10 * 1024 * 1024) {
          _showSnackBar('Image size exceeds 10MB. Please take another photo.',
              isError: true);
          return;
        }
        ref
            .read(selectedImagesProvider.notifier)
            .update((state) => [...state, imageFile]);
      }
    } catch (e) {
      if (e.toString().contains('permission') ||
          e.toString().contains('denied')) {
        _hasPermissionDenied = true;
        _showPermissionDialog();
      } else {
        _showSnackBar('Failed to take photo: ${e.toString().substring(0, 50)}',
            isError: true);
      }
    }
  }

  // 移除图片（修复：添加索引合法性校验，避免数组越界）
  void _removeImage(int index) {
    ref.read(selectedImagesProvider.notifier).update((state) {
      if (index < 0 || index >= state.length) return state; // 边界校验
      final newList = List<File>.from(state);
      newList.removeAt(index);
      return newList;
    });
  }

  // 显示权限申请弹窗（新增：引导用户开启权限）
  void _showPermissionDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: const Color(0xFF2A204A), // 弹窗背景色
        title: const Text(
          'Permission Required',
          style: TextStyle(color: Colors.white), // 弹窗标题颜色
        ),
        content: const Text(
          'We need storage/camera permission to access images. Please enable it in device settings.',
          style: TextStyle(color: Colors.white70), // 弹窗内容颜色
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text(
              'Cancel',
              style: TextStyle(color: Color(0xFF8E44AD)), // 按钮颜色
            ),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              // 跳转到应用设置页面（需集成 permission_handler 插件）
              // await openAppSettings();
            },
            child: const Text(
              'Go to Settings',
              style: TextStyle(color: Color(0xFF27AE60)), // 按钮颜色
            ),
          ),
        ],
      ),
    );
  }

  // 显示提示信息（修复：优化SnackBar显示位置，避免被键盘遮挡）
  void _showSnackBar(String message, {bool isError = false}) {
    if (!mounted) return;

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
          message,
          style: const TextStyle(color: Colors.white), // 文字颜色
        ),
        backgroundColor: isError
            ? const Color(0xFFE74C3C)
            : const Color(0xFF27AE60), // 调整背景色
        duration: const Duration(seconds: 3),
        // 悬浮显示，避免被键盘/底部内容遮挡
        behavior: SnackBarBehavior.floating,
        margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final feedbackType = ref.watch(feedbackTypeProvider);
    final selectedImages = ref.watch(selectedImagesProvider);
    final isSubmitting = ref.watch(isSubmittingProvider);

    return Scaffold(
      backgroundColor: const Color(0xFF211839), // 深蓝紫色背景
      appBar: AppBar(
        backgroundColor: const Color(0xFF211839),
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: const Text(
          'Feedback',
        ),
        centerTitle: false,
      ),
      body: Form(
        key: _formKey,
        // 修复：添加键盘监听，点击空白处收起键盘
        child: GestureDetector(
          onTap: () => FocusScope.of(context).unfocus(),
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildSectionTitle('Feedback Type'),
                const SizedBox(height: 12),
                _buildFeedbackTypeSelector(),
                const SizedBox(height: 24),

                _buildSectionTitle('Describe your feedback'),
                const SizedBox(height: 12),
                _buildContentInput(),
                const SizedBox(height: 24),

                _buildSectionTitle('Attach Images (Optional)'),
                const SizedBox(height: 12),
                _buildImageSection(),
                const SizedBox(height: 24),

                _buildSectionTitle('Contact Information (Optional)'),
                const SizedBox(height: 12),
                _buildContactInput(),
                const SizedBox(height: 32),

                _buildSubmitButton(isSubmitting),
                const SizedBox(height: 16), // 底部留白，避免按钮被遮挡
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 构建section标题（保留原有逻辑）
  Widget _buildSectionTitle(String title) {
    return Text(
      title,
      style: const TextStyle(
        fontSize: 16,
        fontWeight: FontWeight.w600,
        color: Colors.white, // 调整文字颜色
      ),
    );
  }

  // 构建反馈类型选择器（保留原有逻辑，优化选中态样式）
  Widget _buildFeedbackTypeSelector() {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0xFF2A204A), // 次级背景色
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
              color: Colors.black.withOpacity(0.2), // 调整阴影颜色
              blurRadius: 10,
              offset: const Offset(0, 2)),
        ],
      ),
      child: Column(
        children: FeedbackType.values.map((type) {
          final isSelected = ref.watch(feedbackTypeProvider) == type;
          return InkWell(
            onTap: () => ref.read(feedbackTypeProvider.notifier).state = type,
            borderRadius: BorderRadius.circular(12),
            child: Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: isSelected
                    ? type.color.withOpacity(0.2) // 调整选中背景透明度
                    : Colors.transparent,
                borderRadius: BorderRadius.circular(12),
                border:
                    isSelected ? Border.all(color: type.color, width: 2) : null,
              ),
              child: Row(
                children: [
                  Icon(type.icon,
                      color:
                          isSelected ? type.color : Colors.grey[400], // 调整图标颜色
                      size: 24),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      type.label,
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight:
                            isSelected ? FontWeight.w600 : FontWeight.normal,
                        color: isSelected ? type.color : Colors.white, // 调整文字颜色
                      ),
                    ),
                  ),
                  if (isSelected)
                    Icon(Icons.check_circle, color: type.color, size: 20),
                ],
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  // 构建反馈内容输入框（保留原有逻辑）
  Widget _buildContentInput() {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0xFF2A204A), // 次级背景色
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
              color: Colors.black.withOpacity(0.2), // 调整阴影颜色
              blurRadius: 10,
              offset: const Offset(0, 2)),
        ],
      ),
      child: TextFormField(
        controller: _contentController,
        maxLines: 6,
        minLines: 3, // 新增：设置最小行数，提升初始显示体验
        style: const TextStyle(color: Colors.white), // 输入文字颜色
        decoration: const InputDecoration(
          hintText: 'Please describe your feedback in detail...',
          border: InputBorder.none,
          contentPadding: EdgeInsets.all(16),
          hintStyle: TextStyle(color: Colors.grey), // 提示文字颜色
        ),
        validator: (value) {
          if (value == null || value.trim().isEmpty) {
            return 'Please enter your feedback';
          }
          if (value.trim().length < 10) {
            return 'Please provide more details (at least 10 characters)';
          }
          return null;
        },
        enabled: !ref.watch(isSubmittingProvider), // 提交中禁用输入
      ),
    );
  }

  // 构建图片上传区域（修复：语法错误、布局溢出）
  Widget _buildImageSection() {
    final selectedImages = ref.watch(selectedImagesProvider);

    return Container(
      decoration: BoxDecoration(
        color: const Color(0xFF2A204A), // 次级背景色
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
              color: Colors.black.withOpacity(0.2), // 调整阴影颜色
              blurRadius: 10,
              offset: const Offset(0, 2)),
        ],
      ),
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 使用单一GridView包含所有图片和添加按钮
          GridView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              crossAxisSpacing: 8,
              mainAxisSpacing: 8,
              childAspectRatio: 1.0,
            ),
            // 如果图片数量小于3，则添加一个添加按钮
            itemCount: selectedImages.length < 3
                ? selectedImages.length + 1
                : selectedImages.length,
            itemBuilder: (context, index) {
              // 如果是最后一个位置且图片数量小于3，显示添加按钮
              if (index == selectedImages.length && selectedImages.length < 3) {
                return InkWell(
                  onTap: _showImagePickerOptions,
                  borderRadius: BorderRadius.circular(8),
                  child: Container(
                    decoration: BoxDecoration(
                      border: Border.all(
                          color: Colors.grey[500]!, // 调整边框颜色
                          style: BorderStyle.solid,
                          width: 2),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: const Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(Icons.add_photo_alternate_outlined,
                              size: 32, color: Colors.grey),
                          SizedBox(height: 4),
                          Text('Add Image',
                              style:
                                  TextStyle(color: Colors.grey, fontSize: 14)),
                        ],
                      ),
                    ),
                  ),
                );
              }

              // 否则显示已选择的图片
              return Stack(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: Image.file(
                      selectedImages[index],
                      fit: BoxFit.cover,
                      width: double.infinity,
                      height: double.infinity,
                      errorBuilder: (context, error, stackTrace) {
                        return Container(
                          color: Colors.grey[600], // 调整错误显示背景色
                          child: const Icon(Icons.broken_image,
                              color: Colors.grey),
                        );
                      },
                    ),
                  ),
                  Positioned(
                    top: 4,
                    right: 4,
                    child: GestureDetector(
                      onTap: () => _removeImage(index),
                      child: Container(
                        padding: const EdgeInsets.all(4),
                        decoration: const BoxDecoration(
                            color: Colors.red, shape: BoxShape.circle),
                        child: const Icon(Icons.close,
                            color: Colors.white, size: 16),
                      ),
                    ),
                  ),
                ],
              );
            },
          ),

          // 图片数量提示
          if (selectedImages.isNotEmpty)
            Padding(
              padding: const EdgeInsets.only(top: 8),
              child: Text(
                '${selectedImages.length}/3 images selected',
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.grey[400], // 调整提示文字颜色
                ),
              ),
            ),
        ],
      ),
    );
  }

  // 显示图片选择选项（保留原有逻辑，优化底部弹窗样式）
  void _showImagePickerOptions() {
    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        // 添加顶部圆角
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      backgroundColor: const Color(0xFF2A204A), // 弹窗背景色
      builder: (BuildContext context) {
        return SafeArea(
          child: Padding(
            padding: const EdgeInsets.symmetric(vertical: 8),
            child: Wrap(
              children: [
                ListTile(
                  leading:
                      const Icon(Icons.photo_library, color: Color(0xFF4A90E2)),
                  title: const Text(
                    'Choose from Gallery',
                    style: TextStyle(color: Colors.white), // 调整文字颜色
                  ),
                  onTap: () {
                    Navigator.pop(context);
                    _pickImage();
                  },
                ),
                ListTile(
                  leading:
                      const Icon(Icons.photo_camera, color: Color(0xFF4A90E2)),
                  title: const Text(
                    'Take a Photo',
                    style: TextStyle(color: Colors.white), // 调整文字颜色
                  ),
                  onTap: () {
                    Navigator.pop(context);
                    _takePhoto();
                  },
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  // 构建联系方式输入框（修复：手机号正则过严格）
  Widget _buildContactInput() {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0xFF2A204A), // 次级背景色
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
              color: Colors.black.withOpacity(0.2), // 调整阴影颜色
              blurRadius: 10,
              offset: const Offset(0, 2)),
        ],
      ),
      child: TextFormField(
        controller: _contactController,
        style: const TextStyle(color: Colors.white), // 输入文字颜色
        decoration: const InputDecoration(
          hintText: 'Email or phone number (optional)',
          border: InputBorder.none,
          contentPadding: EdgeInsets.all(16),
          hintStyle: TextStyle(color: Colors.grey), // 提示文字颜色
          prefixIcon: Icon(Icons.contact_mail_outlined, color: Colors.grey),
        ),
        validator: (value) {
          if (value == null || value.trim().isEmpty) return null; // 可选字段，空值直接通过

          // 修复：优化手机号正则（支持国内11位手机号，允许带+86）
          final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
          final phoneRegex = RegExp(r'^(?:\+86)?1[3-9]\d{9}$');

          if (!emailRegex.hasMatch(value) && !phoneRegex.hasMatch(value)) {
            return 'Please enter a valid email';
          }
          return null;
        },
        enabled: !ref.watch(isSubmittingProvider),
      ),
    );
  }

  // 构建提交按钮（保留原有逻辑，优化禁用样式）
  Widget _buildSubmitButton(bool isSubmitting) {
    return SizedBox(
      width: double.infinity,
      height: 50,
      child: ElevatedButton(
        onPressed: isSubmitting
            ? null
            : () async {
                if (!_formKey.currentState!.validate()) return;

                ref.read(isSubmittingProvider.notifier).state = true;

                try {
                  // TODO: 实现提交反馈的具体逻辑
                  await Future.delayed(const Duration(seconds: 2)); // 模拟网络请求

                  if (!mounted) return;

                  _showSnackBar('Feedback submitted successfully');
                  Navigator.pop(context);
                } catch (e) {
                  _showSnackBar('Failed to submit feedback: ${e.toString()}',
                      isError: true);
                } finally {
                  if (mounted) {
                    ref.read(isSubmittingProvider.notifier).state = false;
                  }
                }
              },
        style: ElevatedButton.styleFrom(
          backgroundColor: const Color(0xFF8E44AD), // 紫色主题按钮
          foregroundColor: Colors.white,
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          elevation: 2,
          // 新增：禁用时的样式，提升用户感知
          disabledBackgroundColor: const Color(0xFF8E44AD).withOpacity(0.6),
          disabledForegroundColor: Colors.white.withOpacity(0.8),
        ),
        child: isSubmitting
            ? const Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor:
                              AlwaysStoppedAnimation<Color>(Colors.white))),
                  SizedBox(width: 12),
                  Text('Submitting...'),
                ],
              )
            : const Text(
                'Submit Feedback',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
              ),
      ),
    );
  }
}
